import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Divider, Dropdown, Menu, message, Modal, Popconfirm} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm, { FormValueType } from './components/UpdateForm';
import ResetPassword from './components/resetPassord';
import { TableListItem } from './data.d';
import { queryRule, updateRule, addRule, removeRule, resetPasswordRule } from './service';

interface TableListProps extends FormComponentProps { }

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: any) => {
  const hide = message.loading('正在添加');
  try {
    // 请求接口
    await addRule({
      id: fields.id,
    });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在更新');
  try {
    // 请求接口
    await updateRule({
      id: fields.id,
      // phone: fields.phone,
      // email: fields.email,
      // nickname: fields.nickname,
      // remark: fields.remark,
      // rank_num: fields.rank_num,
    });
    hide();

    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      ids: selectedRows.map(row => row.id).join(','),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const TableList: React.FC<TableListProps> = () => {
  const [apiState, setApiState] = useState<any>({common:{}});
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef<ActionType>();
  //重置密码弹窗
  const [passWordVisible, setPassWordVisible] = useState<boolean>(false)
  const [passwordValue, setPasswordValue] = useState({});

  const [userInfo, setUserInfo] = useState<any>({});
    useEffect(()=>{
        const info: any = localStorage.getItem('user-login-info');
        const uInfo = eval(`(${info})`);
        console.log(uInfo.login_name);
        setUserInfo(uInfo);
    },[])

  // 重置密码表单提交
  const handleSubmitDataForm = (value: any) => {
    return new Promise((resolve, reject) => {
      let s = resetPasswordRule(value);
      resolve(s);
    }).then(status => {
      console.log("handleSubmitDataForm status is ", status)
      if (status) {
        setPassWordVisible(false)
        setPasswordValue({})
        message.success("重置密码成功");
        if (actionRef.current) {
          actionRef.current.reload();
        }
      } else {
        message.error(status.msg);
      }
      // 返回执行结果:boolean, 子组件接收此值来重置数据
      return status;
    })
  }

  // 请求接口数据, 设置组件状态
  const getTableData = (params:any) => {
    return queryRule(params).then((res:any) => {
        setApiState(res.data)
        return res.data.listData
    })
  }

  const removeItem = (id:any) => {
    var params = {
      ids: id,
  }
  removeRule(params).then(res=>{
      if(res.code == 0){
          message.success('删除成功！')
          if (actionRef.current) {
              actionRef.current.reload();
          }
      }else{
          message.error(res.msg)
      }
      
  })
  }

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '用户ID',
      dataIndex: 'id',
    },
    {
      title: '登录名',
      dataIndex: 'login_name',
      hideInTable: true,
      hideInSearch: true,
    },
    // {
    //   title: '头像',
    //   dataIndex: 'file_url',
    //   hideInSearch: true,
    //   render: (value, record) => (
    //     <img src={record.file_url} width='50px' />
    //   )
    // },
    {
      title: '手机',
      dataIndex: 'phone',
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    // {
    //   title: '备注',
    //   dataIndex: 'remark',
    //   hideInSearch: true,
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <Popconfirm
            title="确认删除吗？"
            onConfirm={()=>{removeItem(record.id);}}
            okText="确认"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        headerTitle="列表"
        actionRef={actionRef}
        rowKey="key"
        search={false}
        toolBarRender={(action, { selectedRows }) => [
          <Button icon={<PlusOutlined />} type="primary" onClick={() => handleModalVisible(true)}>
            新建
          </Button>,
          selectedRows && selectedRows.length > 0 && (
            <Dropdown
              overlay={
                <Menu
                  onClick={async e => {
                    if (e.key === 'remove') {
                      await handleRemove(selectedRows);
                      action.reload();
                    }
                  }}
                  selectedKeys={[]}
                >
                  <Menu.Item key="remove">删除</Menu.Item>
                </Menu>
              }
            >
              <Button>
                批量操作 <DownOutlined />
              </Button>
            </Dropdown>
          ),
        ]}
        request={params => getTableData(params)}
        columns={columns}
        // rowSelection={{
        //   getCheckboxProps: (record: any) => ({
        //     disabled: record.login_name === userInfo.login_name, // Column configuration not to be checked
        //     login_name: record.login_name,
        //   }),
        // }}
      />
      <CreateForm
        onSubmit={async value => {
          const success = await handleAdd(value);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        common={apiState.common || {}}
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      />
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <UpdateForm
          onSubmit={async value => {
            const success = await handleUpdate(value);
            if (success) {
              handleModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={stepFormValues}
        />
      ) : null}
      <ResetPassword
        passWordVisible={passWordVisible}
        passwordValue={passwordValue}
        onSubmit={async formValue => handleSubmitDataForm(formValue)}
        onCancel={() => setPassWordVisible(false)}
      />
    </PageHeaderWrapper>
  );


};

export default Form.create<TableListProps>()(TableList);
